import { userToLoginType } from '../store/interface'
import { SET_TGT_TOKEN, SET_TOKEN, SET_USER_HOW_TO_LOGIN } from '../store/types'
import store from '@/store'
import { SET_NAV_OPTIONS } from '@/store/types'
import { hideLoading, msg, showLoading, showModal } from '../utils/tools'
import { validateAuthApi } from '@/api/auth'
import { useClearUserInfo } from './user'
import { CURRENT_WEB_OPWENED } from '@/utils/storageTypes'

import { throttle } from '@/utils/common'
import { usePlatform } from './usePlatform'
import { Platform } from '@/interface'

const enum NavigateWay {
  h5 = '1',
  mini = '0',
  owner = '2',
}

// 跳转webview
export const openWeb = throttle(async function (item: Index.ServerData) {
  showLoading()
  let {
    // 跳转地址
    url,
    // 是否需要授权
    authType,
    // 维护中
    inMaintenance,
    // 维护内容
    maintenanceDesc,
    // 是否需要实名
    sensitiveType,
    type,
    tempIds,
  } = item
  console.log(item)
  if (inMaintenance) {
    hideLoading()
    return uni.navigateTo({
      url: `/pagePublic/building/building?msg=${maintenanceDesc || ''}`,
    })
  }
  const userInfo = uni.getStorageSync('userInfo') || null
  const token =
    uni.getStorageSync('threePartLoginData')?.tgt ||
    store.state.user.TGT ||
    null
  if (!url) {
    hideLoading()
    return msg('服务地址获取失败，请稍后再试！')
  }
  url = url
  if ('' + type === NavigateWay.mini) {
    // 小程序跳转
    hideLoading()
    return uni.navigateToMiniProgram({
      appId: item.url,
      path: '',
      envVersion: 'release',
      fail: (err: any) => {
        msg('打开小程序失败，请联系管理员')
      },
    })
  }
  // 内部跳转
  if ('' + type === NavigateWay.owner) {
    hideLoading()
    return uni.navigateTo({
      url: item.url,
    })
  }
  // 鉴权
  if (authType && token) {
    try {
      await validateAuth()
    } catch (e) {
      store.commit(`config/${SET_NAV_OPTIONS}`, item)
      hideLoading()
      return useLogin(userToLoginType.openWeb)
    }
  }
  // 需要登录
  if (authType && !token) {
    // console.log('item------', item)
    store.commit(`config/${SET_NAV_OPTIONS}`, item)
    hideLoading()
    return useLogin(userToLoginType.openWeb)
  }
  // 判断是否需要实名
  if (
    sensitiveType &&
    (!userInfo || !userInfo.level || +userInfo.level !== 2)
  ) {
    hideLoading()
    try {
      store.commit(`config/${SET_NAV_OPTIONS}`, item)
      if (!token) {
        return useLogin(userToLoginType.openWeb)
      }
      await showModal({
        content: '当前服务需要实名，是否继续',
      })
      uni.navigateToMiniProgram({
        appId:
          usePlatform() === Platform.alipay
            ? '2018110962097620'
            : 'wx65813e92ccd10f2f',
        path: '/pageAuth/realAuth/realAuth',
        extraData: {},
      })
    } catch (error) {
      store.commit(`config/${SET_NAV_OPTIONS}`, null)
    }
    return
  }

  useClearLoginChannelRelations()
  uni.setStorageSync(CURRENT_WEB_OPWENED, item)
  hideLoading()
  uni.navigateTo({
    url: `/pagePublic/public/webview?url=${encodeURIComponent(
      url
    )}&auth=${authType}`,
  })
}, 2000)

// 跳转登录
export const useLogin = (type: userToLoginType = userToLoginType.none) => {
  useClearUserInfo()
  store.commit(`user/${SET_USER_HOW_TO_LOGIN}`, type)
  if (type === userToLoginType.none) {
    store.commit(`config/${SET_NAV_OPTIONS}`, null)
  }

  uni.navigateTo({
    url: '/pageAuth/login/login',
  })
}

// 授权之后回调webview
export const useAuthWebview = () => {
  const openWebOption = store.state.config.shouldRedirect
  const isShouldRedirect = store.state.user.userToLoginType

  if (isShouldRedirect === userToLoginType.openWeb && openWebOption) {
    openWeb(openWebOption)
  }
}

// 判断来源是否是 openWeb方法
export const useClearLoginChannelRelations = () => {
  store.commit(`user/${SET_USER_HOW_TO_LOGIN}`, userToLoginType.none)
  store.commit(`config/${SET_NAV_OPTIONS}`, null)
}

// 鉴权
export const validateAuth = async () => {
  try {
    const { data } = await validateAuthApi()
    if (data) {
      return Promise.resolve(true)
    }

    return Promise.reject(false)
  } catch (e) {
    //TODO handle the exception
    return Promise.reject(false)
  }
}

// 鉴权
export const checkAuthSync = async () => {
  showLoading()
  try {
    const { data } = await validateAuthApi()
    if (data) {
      return Promise.resolve(true)
    }

    useLogin(userToLoginType.openWeb)
    hideLoading()
    return Promise.reject(false)
  } catch (e) {
    useLogin(userToLoginType.openWeb)
    hideLoading()
    return Promise.reject(false)
  }
}
